package edu.neusoft.yiqibike.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import edu.neusoft.yiqibike.common.annotation.LoginUser;
import edu.neusoft.yiqibike.common.entity.AdminRole;
import edu.neusoft.yiqibike.common.entity.RolePermission;
import edu.neusoft.yiqibike.common.entity.mysql.Admin;
import edu.neusoft.yiqibike.common.entity.mysql.Permission;
import edu.neusoft.yiqibike.common.entity.mysql.Role;
import edu.neusoft.yiqibike.common.entity.vo.Response;
import edu.neusoft.yiqibike.common.entity.vo.TreeVo;
import edu.neusoft.yiqibike.common.exception.ArgumentVerifyException;
import edu.neusoft.yiqibike.service.IAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * User：lyc
 * Date：2017-12-30
 * Time：14:11
 * Description：
 */
@RestController
@RequestMapping("/sys/autho")
public class AuthorizationController {
    @Autowired
    private IAuthorizationService authorizationService;

    @GetMapping("/tree/{id}")
    public Response<List<TreeVo>> getTreeList(@PathVariable(name = "id") Long aid) {
        if (Objects.isNull(aid)) {
            throw new ArgumentVerifyException("【非法参数】：aid");
        }
        return Response.success(Arrays.asList(authorizationService.getTreeList(aid)));
    }

    @PostMapping("/addRole/{id}")
    public Response<String> addRoleWithId(@PathVariable(name = "id") Long aid, @RequestBody TreeVo roleVo, @LoginUser Admin admin) {
        if (Objects.isNull(aid)) {
            throw new ArgumentVerifyException("【非法参数】：aid");
        }
        Long rid = authorizationService.addRole(aid, roleVo, admin);
        if (Objects.isNull(rid)) {
            return Response.failed();
        }
        return Response.success(String.valueOf(rid));
    }

    @PostMapping("/addPermission/{id}")
    public Response<String> addPermissionWithId(@PathVariable(name = "id") Long rid, @RequestBody TreeVo permissionVo, @LoginUser Admin admin) {
        Long pid = authorizationService.addPermission(rid, permissionVo, admin);
        if (Objects.isNull(pid)) {
            return Response.failed();
        }
        return Response.success(String.valueOf(pid));
    }

    @DeleteMapping("/removeRole/{rid}/{aid}")
    public Response<String> removeRole(@PathVariable Long rid, @PathVariable Long aid) {
        new AdminRole().delete(new EntityWrapper().eq("aid", aid).eq("rid", rid));
        return Response.success();
    }

    @DeleteMapping("/removePermission/{pid}/{rid}")
    public Response<String> removePermission(@PathVariable Long pid, @PathVariable Long rid) {
        new RolePermission().delete(new EntityWrapper().eq("pid", pid).eq("rid", rid));
        return Response.success();
    }

    @GetMapping("/getRoles/{aid}")
    public Response<Map<String, List>> getRoles(@PathVariable Long aid) {
        return Response.success(authorizationService.getRoles(aid));
    }

    @GetMapping("/getPermissions/{aid}")
    public Response<Map<String, List>> getPermissions(@PathVariable Long aid) {
        return Response.success(authorizationService.getPermissions(aid));
    }

    @PutMapping("/updateRole/{aid}")
    public Response<String> updateRole(@PathVariable Long aid, @RequestBody List<Long> rids, @LoginUser Admin admin) {
        if (CollectionUtils.isEmpty(rids)) {
            return Response.success("无角色数据需要维护");
        }
        if (Objects.isNull(aid)) {
            return Response.success("尚未指定管理员");
        }
        authorizationService.updateRole(aid, rids, admin);
        return Response.success();
    }

    @PutMapping("/updatePermission")
    public Response<String> updatePermission(@RequestBody Map<String, List<String>> ids, @LoginUser Admin admin) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.success("无权限数据需要维护");
        }
        List<String> roleCodes = ids.get("roleCodes");
        if (CollectionUtils.isEmpty(roleCodes)) {
            return Response.success("尚未指定角色");
        }
        List<Role> roles = new Role().selectList(new EntityWrapper().in("code", roleCodes));
        List<String> pids = ids.get("pids");
        List<Long> pidList = new ArrayList<>(pids.size());
        for (String pid : pids) {
            pidList.add(Long.valueOf(pid));
        }
        if (CollectionUtils.isEmpty(roles)) {
            return Response.success("角色不存在");
        }
        if (CollectionUtils.isEmpty(pids)) {
            return Response.success("无权限数据需要维护");
        }
        for (Role role : roles) {
            authorizationService.updatePermission(role.getId(), pidList, admin);
        }
        return Response.success();
    }

    @PostMapping("/role/add")
    public Response<String> addRole(@RequestBody Role role) {
        return role.insert() ? Response.success() : Response.failed();
    }

    @PostMapping("/permission/add")
    public Response<String> addPermission(@RequestBody Permission permission) {
        return permission.insert() ? Response.success() : Response.failed();
    }
}
